package com.example.controller.shiro;

import com.example.bean.shiro.ResponseBean;
import com.example.service.shiro.SysUserService;

import com.example.util.shiro.RedisUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2020/6/2 22:00
 */
@RestController
public class TestWebController {


    /**
     *  username    password    role
     *  admin       123456      admin
     *  test22      123456      hr
     */

    private static final Logger log = LoggerFactory.getLogger(TestWebController.class);

    final SysUserService userService;

    final RedisUtil redisUtil;

    @Autowired
    public TestWebController(SysUserService userService, RedisUtil redisUtil) {
        this.userService = userService;
        this.redisUtil = redisUtil;
    }


    /**
     *        curl --location --request GET 'http://localhost:8081/article' \
     *             --header 'Cookie: JSESSIONID=50F0FE80F5C18F44FB8707C25065AAE8' \
     * 获取是否登录信息
     * @return
     */
    @GetMapping("/article")
    public ResponseBean article() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            return new ResponseBean(200, "You are already logged in", subject.toString());
        } else {
            return new ResponseBean(200, "You are guest", subject);
        }
    }

    /**
     * 需要登录
     * @return
     */
    @GetMapping("/require_auth")
    @RequiresAuthentication
    public ResponseBean requireAuth() {
        return new ResponseBean(200, "You are authenticated", null);
    }

    /**
     * 需要角色
     * @return
     */
    @GetMapping("/require_role")
    @RequiresRoles(logical=Logical.OR,value = {"admin","hr"})
    public ResponseBean requireRole() {
        return new ResponseBean(200, "You are visiting require_role admin or hr", null);
    }

    /**
     * 需要权限
     * @return
     */
    @GetMapping("/require_permission")
    @RequiresPermissions(logical = Logical.AND, value = {"roleSettings", "role::list"})
    public ResponseBean requirePermission() {
        return new ResponseBean(200, "You are visiting permission require roleSettings,role::list", null);
    }

    /**
     *  curl --location --request GET 'http://localhost:8081/article' \
     *       --form 'username="test22"' \
     *       --form 'password="123456"'
     * @param request
     * @param map
     * @return
     * @throws Exception
     */

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map<String, Object> map) throws Exception{
        log.info("LoginController.login()");
        // 登录失败从request中获取shiro处理的异常信息。
        String exception = (String) request.getAttribute("shiroLoginFailure");
        log.info("exception=" + exception);
        String msg = "";
        if (exception != null) {
            if (UnknownAccountException.class.getName().equals(exception)) {
                log.error("UnknownAccountException -- > 账号不存在：");
                msg = "UnknownAccountException -- > 账号不存在：";
            } else if (IncorrectCredentialsException.class.getName().equals(exception)) {
                log.error("IncorrectCredentialsException -- > 密码不正确：");
                msg = "IncorrectCredentialsException -- > 密码不正确：";
            } else if ("kaptchaValidateFailed".equals(exception)) {
                log.error("kaptchaValidateFailed -- > 验证码错误");
                msg = "kaptchaValidateFailed -- > 验证码错误";
            }  else if (AuthenticationException.class.getName().equals(exception)) {
                log.error("身份验证出现异常 -- > ");
                msg = "身份验证出现异常 ";
            } else {
                msg = "else >> "+exception;
                log.error("else -- >" + exception);
            }
        }
        map.put("msg", msg);
        // 此方法不处理登录成功,由shiro进行处理
        return "/login";
    }


    /**
     * 组合权限条件
     * @return
     */
    @RequestMapping("/accountCenter1")
    @RequiresRoles(logical=Logical.OR,value = {"admin","hr"})
    @RequiresPermissions(value = {"accountCenter"})
    public String accountCenter1(){
        return "  roles has (admin or hr)  and  permissions has accountCenter";
    }
    /**
     * 组合权限条件
     * @return
     */
    @RequestMapping("/accountCenter2")
    @RequiresRoles(value = {"admin"})
    @RequiresPermissions(value = {"accountCenter"})
    public String accountCenter2(){
        return "roles has admin and   permissions has accountCenter";
    }

}
